/*  GStruct: data structure helpers for Java
 *  Copyright (C) 2011 Giulio Franco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package gstruct.cli;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Base class for parse results
 * @author Giulio Franco <giulio_franco@msn.com>
 *
 * @param <ResultType>	Type of the processed result
 */
public class ParseResult<ResultType> {
	private Boolean ok = null;
	private final ResultType result;
	private final List<ParseError<? super ResultType>> errors = new ArrayList<>();
	private final Collection<CLIArgument<? super ResultType>> arguments;

	/**
	 * Creates a ParseResult
	 * @param result Result object
	 */
	public ParseResult(ResultType result) {
		this.result = result;
		this.arguments = new ArrayList<>();
	}
	
	/**
	 * Checks if the parse was successful
	 * @return	True iff the parse was successful
	 * @throws IllegalStateException if the parse has not been completed yet
	 */
	public boolean isOk() {
		if (ok == null) {
			throw new IllegalStateException("Parse not ended yet");
		} else {
			return ok;
		}
	}
	
	/**
	 * Sets the result of the parse
	 * @param ok Outcome of the parse
	 */
	public void setOk(boolean ok) {
		if (this.ok == null) {
			this.ok = ok;
		} else {
			throw new IllegalStateException("Status cannot be set twice");
		}
	}

	/**
	 * Gets the result of the parse
	 * @return	Result of the parse
	 */
	public ResultType getResult() {
		return result;
	}
	
	/**
	 * Gets the errors produced during the parse
	 * @return	List of parse errors
	 */
	public List<ParseError<? super ResultType>> getErrors() {
		return errors;
	}
	
	/**
	 * Adds an error to the result
	 * @param err New error
	 */
	public void addError(ParseError<? super ResultType> err) {
		errors.add(err);
	}

	/**
	 * Gets the parsed arguments
	 * @return List of the parsed arguments
	 */
	public Collection<CLIArgument<? super ResultType>> getArguments() {
		return Collections.unmodifiableCollection(arguments);
	}

	/**
	 * Adds an argument to the result
	 * @param arg Newly parsed argument
	 */
	void addArgument(CLIArgument<? super ResultType> arg) {
		arguments.add(arg);
	}
}